package com.gxuwz.Market.business.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Repository;

import com.gxuwz.Market.business.entity.TemplateUpload;
import com.gxuwz.Market.business.entity.SysUser;
import com.gxuwz.core.dao.impl.BaseDaoImpl;
import com.gxuwz.core.pagination.Result;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/*
 * 用于上传文件
 */
@Repository("serviceUploadDAO")
public class ServiceUploadDAO extends BaseDaoImpl<TemplateUpload>{
	/**
	 * 根据获取的文件和文件名保存到数据库
	 * @return
	 * @author 黄森南
	 * @throws IOException 
	 * @date 2018.01.22
	 */

public   TemplateUpload upload_file;//声明一个实体，用于保存上传的信息
	public   void  fileUpload(File file,String fileFileName,String fileContentType) throws IOException
	{
		
		  String savePath =ServletActionContext.getServletContext().getRealPath("/WEB-INF/uploadFile");
	       String newName =fileFileName; //(1)文件名
	        //获取需要上传文件的文件路径  
	        File uploadFile=new File(savePath);  
	        //判断文件是否上传，如果上传的话将会创建该目录  
	      
	        if(!uploadFile.exists()){  
	            uploadFile.mkdir(); //创建该目录  
	        }   
	        //第一种文件上传的方法  
	        //声明文件输入流，为输入流指定文件路径  
	        FileInputStream input=new FileInputStream(file);  //(2)文件
	        //获取输出流，获取文件的文件地址及名称  
	        FileOutputStream out=new FileOutputStream(uploadFile + "\\" +newName); //保存路径
	        SysUser sysUser =(SysUser) ActionContext.getContext().getSession().get("sysUser");//获取登录人的用户名
	        Timestamp now = new  Timestamp(new Date().getTime());
		      if(upload_file==null)
		      {
		    	  upload_file=new TemplateUpload();
		      }
		      try{
	       upload_file.setOperator(sysUser.getUserId());
	       upload_file.setFileFileName(fileFileName);
	       upload_file.setFileContentType(fileContentType);
	       upload_file.setFilePath(uploadFile + "\\" +newName);
	       upload_file.setUploadTime(now);
	       getHibernateTemplate().save(upload_file);
		      }catch(Exception e)
		      {
		    	  e.printStackTrace();
		      }
	        try{  
	            byte[] b=new byte[1024];//每次写入的大小  
	            int i=0;  
	            while((i=input.read(b))>0){  
	                out.write(b,0,i);  
	            }  
	        }catch(Exception e){  
	            e.printStackTrace();  
	        }finally{  
	            input.close();  
	            out.close();  
	        }     	          
	}
	
	public Result findAll(Integer page, Integer size) {
		
		String hql="from  TemplateUpload where 1=1";
		int start=(page-1)*size;
		int limit =size;
		return super.find(hql, null, null, start, limit);
	}
	
	}




